import React, { useEffect } from 'react';
import {
  Container,
  Grid,
  CssBaseline,
  Paper,
  Tabs,
  Tab,
  Box,
  Avatar,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Snackbar,
  Alert,
  CircularProgress,
  Pagination
} from '@mui/material';
import { Link, useLocation } from 'react-router-dom';
import Navbar from '../components/Navbar';
import EditIcon from '@mui/icons-material/Edit';
import MailOutlineIcon from '@mui/icons-material/MailOutline';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import PersonRemoveIcon from '@mui/icons-material/PersonRemove';
import { Link as RouterLink } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { 
  generateInviteCode, 
  getMyInviteCodes, 
  checkIn, 
  getCheckInStatus, 
  getBalance,
  getUserInfo,
  getUserStats,
  getUserRecords,
  getUserFollowing,
  getUserFollowers,
  toggleFollowUser,
  updateUserProfile,
  uploadUserAvatar,
  getUploadHistory,
  getDownloadHistory
} from '../api/profile';
import { changePassword, sendPasswordResetCode } from '../api/auth';
import { instance } from '../axios';

import { navigationItems } from '../App';


function Profile() {
  const location = useLocation();
  const navigate = useNavigate();
  
  // 获取URL中的用户查询参数
  const urlParams = new URLSearchParams(location.search);
  const userParam = urlParams.get('user');
  
  // 用户信息状态
  const [userInfo, setUserInfo] = React.useState({
    id: 0,
    avatar: '',
    username: '',
    email: '',
    joinDate: '',
    nickname: '',
    following: 0,
    followers: 0,
    upload: '0',
    download: '0',
    ratio: '0',
    score: 0,
    yangtao: 0,
    level: 1,
    isCurrentUser: false
  });
  
  // 加载状态
  const [loading, setLoading] = React.useState(true);
  
  // 关注状态
  const [isFollowing, setIsFollowing] = React.useState(false);
  
  // 弹窗控制
  const [openDialog, setOpenDialog] = React.useState('');
  
  // 表单状态
  const [form, setForm] = React.useState({
    nickname: '',
    email: '',
    password: '',
    newPassword: '',
    confirmPassword: '',
    avatar: '',
    code: ''
  });
  
  // 表单错误
  const [formError, setFormError] = React.useState({});
  
  // 关注列表
  const [followingList, setFollowingList] = React.useState([]);
  const [followersList, setFollowersList] = React.useState([]);
  
  // 控制列表弹窗
  const [openListDialog, setOpenListDialog] = React.useState(''); // 'following' | 'followers' | ''
  
  // 私信弹窗相关状态
  const [openChat, setOpenChat] = React.useState({ open: false, user: null });
  const [chatInput, setChatInput] = React.useState('');
  const [chatHistory, setChatHistory] = React.useState([]);
  
  // 记录弹窗相关
  const [openRecord, setOpenRecord] = React.useState(false);
  const [recordList, setRecordList] = React.useState([]);
  const [recordType, setRecordType] = React.useState('upload'); // 'upload' 或 'download'
  
  // 新增状态
  const [inviteCodes, setInviteCodes] = React.useState([]);
  const [balance, setBalance] = React.useState(0);
  const [checkedIn, setCheckedIn] = React.useState(false);
  const [snackbar, setSnackbar] = React.useState({
    open: false,
    message: '',
    severity: 'success'
  });
  const [openInviteDialog, setOpenInviteDialog] = React.useState(false);
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    setLoading(true);
    try {
      const userId = userParam || localStorage.getItem('id');
      
      // 判断是否是当前用户
      const isCurrentUser = !userParam || userId === localStorage.getItem('id');
      
      // 从localStorage获取Navbar组件已经获取的用户信息
      let userResponse;
      try {
        const localUser = JSON.parse(localStorage.getItem('user'));
        if (localUser) {
          userResponse = { data: localUser };
          console.log("从localStorage获取的用户信息:", userResponse);
        } else {
          console.log("localStorage中没有用户信息");
          throw new Error('localStorage中没有用户信息');
        }
      } catch (error) {
        console.error("解析localStorage中的用户信息失败:", error);
        throw new Error('获取用户信息失败');
      }

      if (!userResponse || !userResponse.data) {
        console.log("userId: " + userId);
        console.log("isCurrentUser: " + isCurrentUser);
        console.log("userResponse: " + userResponse);
        throw new Error('获取用户信息失败');
      }
      
      // 并行获取其他数据
      const promises = [];
      
      // 获取签到状态
      if (isCurrentUser) {
        promises.push(getCheckInStatus().catch(err => {
          console.error('获取签到状态失败:', err);
          return { data: { checkedToday: false } };
        }));
        
        // 获取邀请码
        promises.push(getMyInviteCodes().catch(err => {
          console.error('获取邀请码失败:', err);
          return { data: { codes: [] } };
        }));
      } else {
        // 非当前用户，添加空占位符
        promises.push(Promise.resolve(null));
        promises.push(Promise.resolve(null));
      }
      
      // 等待所有请求完成
      const [checkInRes, inviteCodesRes] = await Promise.all(promises);
      
      // 处理后端返回的数据
      const userData = userResponse.data;
      
      // 确保所有必要的字段都存在
      const processedData = {
        id: userData.id || 0,
        avatar: userData.avatar || '/default-avatar.png',
        username: userData.username || '',
        email: userData.email || '',
        joinDate: userData.createdAt || '',
        nickname: userData.nickname || userData.username || '',
        following: userData.following || 0,
        followers: userData.followers || 0,
        upload: userData.upload || '0 B',
        download: userData.download || '0 B',
        ratio: userData.ratio || '0',
        score: userData.score || 0,
        yangtao: userData.yangtao || 0,
        level: userData.level || 1
      };
      
      
      // 设置用户信息
      setUserInfo({
        ...processedData,
        isCurrentUser: isCurrentUser
      });
      
      // 设置表单初始值
      setForm({
        nickname: userData.nickname || userData.username || '',
        email: userData.email || '',
        password: '',
        newPassword: '',
        confirmPassword: '',
        code: ''
      });
      
      // 设置签到状态
      if (isCurrentUser && checkInRes && checkInRes.data) {
        setCheckedIn(checkInRes.data.checkedToday || false);
      }
      
      // 设置邀请码
      if (isCurrentUser && inviteCodesRes && inviteCodesRes.data) {
        console.log('处理邀请码数据:', inviteCodesRes);

        // 处理不同的返回格式
        if (inviteCodesRes.data.codes && Array.isArray(inviteCodesRes.data.codes)) {
          // 格式: {data: {codes: Array(n), ...}, ...}
          setInviteCodes(inviteCodesRes.data.codes || []);
        } else if (Array.isArray(inviteCodesRes.data)) {
          // 格式: {data: Array(n), ...}
          setInviteCodes(inviteCodesRes.data || []);
        } else if (inviteCodesRes.data.status === 'success' && inviteCodesRes.data.codes && Array.isArray(inviteCodesRes.data.codes)) {
          // 格式: {data: {status: 'success', codes: Array(n), ...}, ...}
          setInviteCodes(inviteCodesRes.data.codes);
        } else {
          console.error('无法识别的邀请码数据格式:', inviteCodesRes);
          setInviteCodes([]);
        }
      } else if (isCurrentUser && inviteCodesRes) {
        // 处理直接在inviteCodesRes中的数据
        if (inviteCodesRes.codes && Array.isArray(inviteCodesRes.codes)) {
          // 格式: {codes: Array(n), ...}
          setInviteCodes(inviteCodesRes.codes);
        } else if (inviteCodesRes.status === 'success' && inviteCodesRes.codes && Array.isArray(inviteCodesRes.codes)) {
          // 格式: {status: 'success', codes: Array(n), ...}
          setInviteCodes(inviteCodesRes.codes);
        } else if (Array.isArray(inviteCodesRes)) {
          // 直接是数组
          setInviteCodes(inviteCodesRes);
        } else {
          console.error('无法识别的邀请码数据格式:', inviteCodesRes);
          setInviteCodes([]);
        }
      }
      
      // 如果不是当前用户，检查是否已关注
      if (!isCurrentUser) {
        // 这里需要API支持，暂时模拟
        // 实际应该调用API检查当前用户是否已关注目标用户
        setIsFollowing(false);
      }
      
    } catch (error) {
      console.error('获取用户信息失败:', error);
      setSnackbar({
        open: true,
        message: '获取用户信息失败: ' + (error.message || '服务器错误'),
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };
  
  // 获取关注列表
  const fetchFollowingList = async () => {
    try {
      const userId = userParam || localStorage.getItem('id');
      const response = await getUserFollowing(userId);
      
      if (response && response.data) {
        setFollowingList(response.data || []);
      }
    } catch (error) {
      console.error('获取关注列表失败:', error);
    }
  };
  
  // 获取粉丝列表
  const fetchFollowersList = async () => {
    try {
      const userId = userParam || localStorage.getItem('id');
      const response = await getUserFollowers(userId);
      
      if (response && response.data) {
        setFollowersList(response.data || []);
      }
    } catch (error) {
      console.error('获取粉丝列表失败:', error);
    }
  };
  
  // 获取用户记录
  const fetchUserRecords = async (type = 'upload') => {
    try {
      let response;
      
      // 根据类型调用不同的API
      if (type === 'upload') {
        response = await getUploadHistory(userInfo.id);
        console.log(response);
        console.log("上传记录:", response);
      } else if (type === 'download') {
        response = await getDownloadHistory(userInfo.id);
        console.log("下载记录:", response);
      }
      
      console.log(`获取${type}记录:`, response);
      
      if (response && response.data) {
        // 处理后端返回的分页数据
        if (response.data.content) {
          // Spring Data分页格式
          setRecordList(response.data.content || []);
        } else if (Array.isArray(response.data)) {
          // 数组格式
          setRecordList(response.data);
        } else {
          setRecordList([]);
        }
      } else if (Array.isArray(response)) {
        // 直接是数组格式
        setRecordList(response);
      } else {
        setRecordList([]);
      }
    } catch (error) {
      console.error('获取用户记录失败:', error);
      setRecordList([]);
      setSnackbar({
        open: true,
        message: `获取${type === 'upload' ? '上传' : '下载'}记录失败: ${error.message || '服务器错误'}`,
        severity: 'error'
      });
    }
  };

  // 当URL用户参数变化时，更新显示的用户信息
  useEffect(() => {
    fetchUserInfo();
  }, [userParam]);
  
  // 处理关注/取消关注
  const handleFollowToggle = async () => {
    try {
      const action = isFollowing ? 'unfollow' : 'follow';
      const response = await toggleFollowUser(userInfo.id, action);
      
      if (response && response.data) {
        setIsFollowing(!isFollowing);
        
        // 更新关注者数量
        const updatedUser = {
          ...userInfo,
          followers: isFollowing 
            ? Math.max(0, userInfo.followers - 1) 
            : userInfo.followers + 1
        };
        
        setUserInfo(updatedUser);
        
        setSnackbar({
          open: true,
          message: isFollowing ? '已取消关注' : '关注成功',
          severity: 'success'
        });
      } else {
        throw new Error('操作失败');
      }
    } catch (error) {
      console.error('关注操作失败:', error);
      setSnackbar({
        open: true,
        message: '操作失败: ' + (error.message || '服务器错误'),
        severity: 'error'
      });
    }
  };

  // 处理表单输入
  const handleFormChange = (field) => (e) => {
    setForm({ ...form, [field]: e.target.value });
  };

  // 打开弹窗
  const handleOpen = (type) => {
    // 重置表单状态
    if (type === 'nickname') {
      setForm({
        ...form,
        nickname: userInfo.nickname || userInfo.username || ''
      });
    } else if (type === 'password') {
      setForm({
        ...form,
        password: '',
        newPassword: '',
        confirmPassword: '',
        code: ''
      });
    }
    setFormError({});
    setOpenDialog(type);
  };
  
  // 关闭弹窗
  const handleClose = () => setOpenDialog('');

  // 保存用户资料
  const handleSave = async () => {
    let error = {};
    
          if (openDialog === 'nickname') {
      if (!form.nickname) error.nickname = '昵称不能为空';
      
      if (Object.keys(error).length === 0) {
        try {
          // 获取用户ID
          const userId = userInfo.id || localStorage.getItem('id');
          
          console.log("Updating nickname with:", {
            userId: userId,
            nickname: form.nickname
          });
          
          // 只传递用户ID和昵称
          const response = await updateUserProfile({
            id: userId,
            nickname: form.nickname
          });
          
          console.log("Nickname update response:", response);
          
                    console.log("完整响应:", response);
          
          // 更宽松地检查成功响应
          // 如果状态码是200，我们就认为是成功的
          const isSuccess = 
            (response && response.status >= 200 && response.status < 300) || 
            (response && response.data && response.data.status === 'success') || 
            (response && response.data && response.data.message === '用户名修改成功') ||
            (response && response.data && response.data.msg);
          
          if (isSuccess) {
            console.log("昵称修改成功，更新用户信息");
            
            // 更新用户信息中的昵称和用户名
            setUserInfo({ 
              ...userInfo, 
              nickname: form.nickname,
              username: form.nickname // 同时更新username，因为后端实际上是更新的username
            });
            
            // 更新localStorage中的username
            localStorage.setItem('username', form.nickname);
            
            setSnackbar({
              open: true,
              message: (response.data && response.data.message) || '昵称修改成功',
              severity: 'success'
            });
            handleClose();
          } else {
            console.error("昵称修改失败，响应不符合预期:", response);
            throw new Error('修改失败');
          }
        } catch (err) {
          console.error('修改昵称失败:', err);
          
          // 详细记录错误信息
          if (err.response) {
            console.log('错误响应数据:', err.response.data);
            console.log('错误状态码:', err.response.status);
            console.log('错误响应头:', err.response.headers);
          }
          
          // 构建更详细的错误消息
          let errorMessage = '服务器错误';
          if (err.response && err.response.data) {
            if (typeof err.response.data === 'string') {
              errorMessage = err.response.data;
            } else if (err.response.data.message) {
              errorMessage = err.response.data.message;
            } else if (err.response.data.msg) {
              errorMessage = err.response.data.msg;
            } else {
              errorMessage = JSON.stringify(err.response.data);
            }
          } else if (err.message) {
            errorMessage = err.message;
          }
          
          setSnackbar({
            open: true,
            message: '修改失败: ' + errorMessage,
            severity: 'error'
          });
        }
      } else {
        setFormError(error);
      }
    } else if (openDialog === 'email') {
      if (!form.email) error.email = '邮箱不能为空';
      else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) error.email = '邮箱格式不正确';
      
      if (Object.keys(error).length === 0) {
        try {
          const response = await updateUserProfile({
            email: form.email
          });
          
          if (response && response.data) {
            setUserInfo({ ...userInfo, email: form.email });
            setSnackbar({
              open: true,
              message: '邮箱修改成功',
              severity: 'success'
            });
            handleClose();
          } else {
            throw new Error('修改失败');
          }
        } catch (err) {
          console.error('修改邮箱失败:', err);
          setSnackbar({
            open: true,
            message: '修改失败: ' + (err.message || '服务器错误'),
            severity: 'error'
          });
        }
      } else {
        setFormError(error);
      }
    } else if (openDialog === 'password') {
      if (!form.password) error.password = '请输入原密码';
      if (!form.newPassword) error.newPassword = '请输入新密码';
      if (form.newPassword !== form.confirmPassword) error.confirmPassword = '两次输入的新密码不一致';
      if (form.password === form.newPassword) error.newPassword = '新密码不能与原密码相同';
      
      // 调试信息
      console.log("Password form validation:", { 
        password: !!form.password,
        newPassword: !!form.newPassword,
        confirmMatch: form.newPassword === form.confirmPassword,
        differentFromOld: form.password !== form.newPassword,
        email: localStorage.getItem('email') || userInfo.email
      });
      
      if (Object.keys(error).length === 0) {
        try {
          // 直接使用instance.post而不是auth.js中的changePassword函数
          // 添加调试信息
          console.log("Sending password change request with email:", userInfo.email);
          
          // 优先使用localStorage中的email，因为这是登录时保存的
          const userEmail = localStorage.getItem('email') || userInfo.email;
          console.log("Using email for password change:", userEmail);
          
          // 使用URLSearchParams格式发送请求参数
          const params = new URLSearchParams();
          params.append('email', userEmail);
          params.append('code', form.code || '');
          params.append('oldPassword', form.password);
          params.append('newPassword', form.newPassword);
          
          console.log("Sending password change with params:", {
            email: userEmail,
            code: form.code || '',
            oldPassword: form.password,
            newPassword: form.newPassword
          });
          
          const response = await instance.post('/usercenter/new-password', params, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          });
          
          console.log("Password change response:", response);
          
          // 检查各种可能的成功响应格式
          const isSuccess = 
            (response && response.data && response.data.status === 'success') || 
            (response && response.status === 200) ||
            (response && response.data && response.data.msg);
            
          if (isSuccess) {
            setSnackbar({
              open: true,
              message: '密码修改成功',
              severity: 'success'
            });
            handleClose();
          } else {
            throw new Error((response.data && response.data.message) || '修改失败');
          }
        } catch (err) {
          console.error('密码修改失败:', err);
          
          // 尝试获取后端返回的具体错误信息
          let errorMessage = '服务器错误';
          if (err.response && err.response.data) {
            if (err.response.data.message) {
              errorMessage = err.response.data.message;
            } else if (typeof err.response.data === 'string') {
              errorMessage = err.response.data;
            } else {
              errorMessage = JSON.stringify(err.response.data);
            }
          } else if (err.message) {
            errorMessage = err.message;
          }
          
          setSnackbar({
            open: true,
            message: '修改失败: ' + errorMessage,
            severity: 'error'
          });
        }
      } else {
        setFormError(error);
      }
    }
  };


  // 打开私信窗口
  const handleOpenChat = (user) => {
    const userForMessage = {
      id: user.id,
      name: user.nickname || user.username,
      avatar: user.avatar,
    };
    navigate('/message', { state: { user: userForMessage } });
  };

  // 关闭私信窗口
  const handleCloseChat = () => setOpenChat({ open: false, user: null });
  
  // 发送消息
  const handleSendChat = () => {
    if (chatInput.trim()) {
      setChatHistory([...chatHistory, { from: '我', content: chatInput }]);
      setChatInput('');
    }
  };

  // 获取用户余额
  const fetchBalance = async () => {
    if (!userInfo.isCurrentUser) return;
    
    try {
      const res = await getBalance();
      if (res && res.data) {
        setBalance(res.data.balance || 0);
        // 同时更新userInfo中的score
        setUserInfo(prev => ({
          ...prev,
          score: res.data.balance || 0
        }));
      }
    } catch (error) {
      console.error('获取余额失败:', error);
    }
  };
  
  // 获取签到状态
  const fetchCheckInStatus = async () => {
    if (!userInfo.isCurrentUser) return;
    
    try {
      const res = await getCheckInStatus();
      if (res && res.data) {
        setCheckedIn(res.data.checkedToday || false);
      }
    } catch (error) {
      console.error('获取签到状态失败:', error);
    }
  };
  
  // 获取邀请码
  const fetchInviteCodes = async () => {
    if (!userInfo.isCurrentUser) return;
    
    try {
      const res = await getMyInviteCodes();
      console.log('获取邀请码响应:', res);
      if (res) {
        // 处理不同的返回格式
        if (res.codes && Array.isArray(res.codes)) {
          // 格式: {codes: Array(n), ...}
          setInviteCodes(res.codes || []);
        } else if (res.data && res.data.codes && Array.isArray(res.data.codes)) {
          // 格式: {data: {codes: Array(n), ...}, ...}
          setInviteCodes(res.data.codes || []);
        } else if (res.data && Array.isArray(res.data)) {
          // 格式: {data: Array(n), ...}
          setInviteCodes(res.data || []);
        } else if (Array.isArray(res)) {
          // 直接是数组
          setInviteCodes(res);
        } else if (res.data && res.data.status === 'success' && res.data.codes && Array.isArray(res.data.codes)) {
          // 格式: {data: {codes: Array(n), status: 'success', ...}, ...}
          setInviteCodes(res.data.codes);
        } else if (res.status === 'success' && res.codes && Array.isArray(res.codes)) {
          // 格式: {status: 'success', codes: Array(n), ...}
          setInviteCodes(res.codes);
        } else {
          console.error('无法识别的邀请码数据格式:', res);
          setInviteCodes([]);
        }
      }
    } catch (error) {
      console.error('获取邀请码失败:', error);
    }
  };
  
  // 生成邀请码
  const handleGenerateInviteCode = async () => {
    try {
      const res = await generateInviteCode();
      console.log('生成邀请码响应:', res);

      // 检查各种可能的成功响应格式
      const isSuccess =
        (res && res.status === 'success') ||
        (res && res.data && res.data.status === 'success');

      if (isSuccess) {
        // 刷新邀请码列表
        fetchInviteCodes();

        // 构建成功消息
        let successMessage = '邀请码生成成功！';
        if (res.code) {
          successMessage += ` 邀请码: ${res.code}`;
        } else if (res.data && res.data.code) {
          successMessage += ` 邀请码: ${res.data.code}`;
        }

        setSnackbar({
          open: true,
          message: successMessage,
          severity: 'success'
        });
      } else {
        setSnackbar({
          open: true,
          message: '邀请码生成失败: ' + (res.message || res.data?.message || '未知错误'),
          severity: 'error'
        });
      }
    } catch (error) {
      console.error('生成邀请码失败:', error);
      setSnackbar({
        open: true,
        message: '生成邀请码失败: ' + (error.response?.data?.message || '服务器错误'),
        severity: 'error'
      });
    }
  };
  
  // 签到
  const handleCheckIn = async () => {
    try {
      const res = await checkIn();
      if (res && res.data) {
        setCheckedIn(true);
        // 刷新余额
        fetchBalance();
        
        // 直接更新积分显示
        const reward = res.data.reward || 0;
        setUserInfo(prev => ({
          ...prev,
          score: (prev.score || 0) + reward
        }));
        
        setSnackbar({
          open: true,
          message: `签到成功！获得 ${reward} 积分`,
          severity: 'success'
        });
      } else {
        setSnackbar({
          open: true,
          message: '签到失败',
          severity: 'error'
        });
      }
    } catch (error) {
      console.error('签到失败:', error);
      setSnackbar({
        open: true,
        message: '签到失败: ' + (error.response?.data?.message || '服务器错误'),
        severity: 'error'
      });
    }
  };
  
  // 关闭提示
  const handleCloseSnackbar = () => {
    setSnackbar({ ...snackbar, open: false });
  };
  
  // 查看记录
  const handleViewRecords = (type) => {
    setRecordType(type);
    fetchUserRecords(type);
    setOpenRecord(true);
  };
  
  // 初始化数据
  useEffect(() => {
    if (userInfo.isCurrentUser) {
      fetchBalance();
      fetchCheckInStatus();
      fetchInviteCodes();
    }
  }, [userInfo.isCurrentUser]);
  
  // 打开关注/粉丝列表时加载数据
  useEffect(() => {
    if (openListDialog === 'following') {
      fetchFollowingList();
    } else if (openListDialog === 'followers') {
      fetchFollowersList();
    }
  }, [openListDialog]);

  return (
    <div className="App" style={{ backgroundColor: '#fefaff', minHeight: '100vh' }}>
      <CssBaseline />
      <Navbar />
      
      <Container
        maxWidth="false"
        sx={{
          backdropFilter: 'blur(4px)',
          backgroundColor: 'rgba(255,255,255,0.6)',
          borderRadius: 3,
          p: 2,
          mt: 3,
        }}
      >
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Tabs
            value={location.pathname}
            indicatorColor="secondary"
            textColor="secondary"
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              borderBottom: '2px solid #f3e5f5',
              mb: 2,
              '& .MuiTab-root': {
                transition: 'all 0.3s ease-in-out',
              },
              '& .Mui-selected': {
                color: '#8e24aa',
                fontWeight: 'bold',
              },
              '& .MuiTabs-indicator': {
                height: 3,
                backgroundColor: '#ce93d8',
                borderRadius: 2,
              }
            }}
          >
            {navigationItems
              .filter(item => !item.adminOnly || (userInfo.role === 'admin'))
              .map((item) => (
              <Tab
                key={item.path}
                label={item.label}
                value={item.path}
                component={Link}
                to={item.path}
                sx={{
                  minWidth: 100,
                  borderRadius: 2,
                  mx: 0.5,
                  transition: 'all 0.3s',
                  color: '#8e24aa',
                  '&:hover': {
                    backgroundColor: '#ffe0f0',
                    color: '#d81b60',
                  },
                  '&.Mui-selected': {
                    fontWeight: 'bold',
                    color: '#d81b60',
                    backgroundColor: '#fff0f5',
                  },
                }}
              />
            ))}
          </Tabs>
        </Box>
      </Container>
      
      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
              <CircularProgress sx={{ color: '#d81b60' }} />
            </Box>
          ) : (
            <>
              <Paper elevation={3} sx={{ 
                p: 3, 
                mb: 4,
                borderRadius: 3,
                background: 'linear-gradient(135deg, #fff0f5 0%, #fce4ec 100%)',
                boxShadow: '0 4px 20px rgba(200, 100, 255, 0.1)',
              }}>
                <Grid container spacing={3}>
                  <Grid item xs={12} md={3} sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                    <Box sx={{ position: 'relative', mb: 2 }}>
                      <Avatar 
                        src={userInfo.avatar} 
                        alt={userInfo.username}
                        sx={{ 
                          width: 150, 
                          height: 150, 
                          border: '4px solid #f8bbd0',
                          boxShadow: '0 4px 10px rgba(200, 100, 255, 0.2)'
                        }}
                      />
                    </Box>
                    <Typography variant="h5" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                      {userInfo.nickname}
                    </Typography>
                    <Typography variant="body2" gutterBottom sx={{ color: '#9e9e9e', mb: 2 }}>
                      @{userInfo.username}
                    </Typography>
                    
                    {!userInfo.isCurrentUser && (
                      <Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
                        <Button
                          variant="contained"
                          startIcon={isFollowing ? <PersonRemoveIcon /> : <PersonAddIcon />}
                          onClick={handleFollowToggle}
                          sx={{
                            borderRadius: 2,
                            background: isFollowing 
                              ? 'linear-gradient(45deg, #f44336 30%, #ff9800 90%)'
                              : 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
                            color: 'white',
                            fontWeight: 'bold',
                            '&:hover': {
                              background: isFollowing
                                ? 'linear-gradient(45deg, #d32f2f 30%, #f57c00 90%)'
                                : 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
                            }
                          }}
                        >
                          {isFollowing ? '取消关注' : '关注'}
                        </Button>
                        <Button
                          variant="outlined"
                          startIcon={<MailOutlineIcon />}
                          onClick={() => handleOpenChat(userInfo)}
                          sx={{
                            borderRadius: 2,
                            borderColor: '#d81b60',
                            color: '#d81b60',
                            '&:hover': {
                              borderColor: '#c2185b',
                              backgroundColor: '#fce4ec',
                              color: '#c2185b'
                            }
                          }}
                        >
                          私信
                        </Button>
                      </Box>
                    )}
                  </Grid>
                  <Grid item xs={12} md={9}>
                    <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                      {userInfo.nickname}
                    </Typography>
                    <Typography color="text.secondary" sx={{ mb: 2 }}>
                      {userInfo.email}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 3, mb: 2 }}>
                      <Typography
                        color="text.secondary"
                        sx={{ fontSize: 15, cursor: 'pointer' }}
                        onClick={() => setOpenListDialog('following')}
                      >
                        正在关注 <b>{userInfo.following}</b>
                      </Typography>
                      <Typography
                        color="text.secondary"
                        sx={{ fontSize: 15, cursor: 'pointer' }}
                        onClick={() => setOpenListDialog('followers')}
                      >
                        关注者 <b>{userInfo.followers}</b>
                      </Typography>
                    </Box>
                  </Grid>
                </Grid>
              </Paper>
              
              {/* 用户统计信息卡片 */}
              <Paper elevation={3} sx={{ 
                p: 3, 
                mb: 4,
                borderRadius: 3,
                background: 'linear-gradient(135deg, #e8f5e9 0%, #e0f2f1 100%)',
                boxShadow: '0 4px 20px rgba(100, 200, 150, 0.1)',
              }}>
                <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                  用户统计
                </Typography>
                <Grid container spacing={3} sx={{ mt: 1 }}>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>上传量</Typography>
                      <Typography variant="h6" sx={{ color: '#4caf50', fontWeight: 'bold' }}>
                        {userInfo.upload || '0 B'}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>下载量</Typography>
                      <Typography variant="h6" sx={{ color: '#2196f3', fontWeight: 'bold' }}>
                        {userInfo.download || '0 B'}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>分享率</Typography>
                      <Typography variant="h6" sx={{ color: '#ff9800', fontWeight: 'bold' }}>
                        {userInfo.ratio || '0'}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>积分</Typography>
                      <Typography variant="h6" sx={{ color: '#d81b60', fontWeight: 'bold' }}>
                        {userInfo.score || 0}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>杨桃</Typography>
                      <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                        {userInfo.yangtao || 0}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Box sx={{ 
                      p: 2, 
                      textAlign: 'center',
                      borderRadius: 2,
                      backgroundColor: 'rgba(255,255,255,0.7)',
                      transition: 'transform 0.3s',
                      '&:hover': {
                        transform: 'translateY(-5px)',
                        boxShadow: '0 10px 20px rgba(200, 100, 255, 0.15)'
                      }
                    }}>
                      <Typography variant="body2" sx={{ color: '#9e9e9e' }}>等级</Typography>
                      <Typography variant="h6" sx={{ color: '#9c27b0', fontWeight: 'bold' }}>
                        {userInfo.level || 1}
                      </Typography>
                    </Box>
                  </Grid>
                </Grid>
              </Paper>
              
              {/* 功能区卡片 - 仅当前用户可见 */}
              {userInfo.isCurrentUser && (
                <Paper elevation={3} sx={{ 
                  p: 3, 
                  mb: 4,
                  borderRadius: 3,
                  background: 'linear-gradient(135deg, #e3f2fd 0%, #e8eaf6 100%)',
                  boxShadow: '0 4px 20px rgba(100, 150, 255, 0.1)',
                }}>
                  <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                    功能区
                  </Typography>
                  <Grid container spacing={3} sx={{ mt: 1 }}>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={() => handleViewRecords('upload')}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: 'linear-gradient(45deg, #42a5f5 30%, #2196f3 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: 'linear-gradient(45deg, #1e88e5 30%, #1976d2 90%)',
                          }
                        }}
                      >
                        上传记录
                      </Button>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={() => handleViewRecords('download')}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: 'linear-gradient(45deg, #42a5f5 30%, #2196f3 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: 'linear-gradient(45deg, #1e88e5 30%, #1976d2 90%)',
                          }
                        }}
                      >
                        下载记录
                      </Button>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={handleCheckIn}
                        disabled={checkedIn}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: checkedIn 
                            ? 'linear-gradient(45deg, #9e9e9e 30%, #757575 90%)'
                            : 'linear-gradient(45deg, #66bb6a 30%, #4caf50 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: checkedIn
                              ? 'linear-gradient(45deg, #9e9e9e 30%, #757575 90%)'
                              : 'linear-gradient(45deg, #43a047 30%, #388e3c 90%)',
                          },
                          '&.Mui-disabled': {
                            color: 'rgba(255,255,255,0.8)'
                          }
                        }}
                      >
                        {checkedIn ? '今日已签到' : '每日签到'}
                      </Button>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={() => setOpenInviteDialog(true)}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: 'linear-gradient(45deg, #42a5f5 30%, #2196f3 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: 'linear-gradient(45deg, #1e88e5 30%, #1976d2 90%)',
                          }
                        }}
                      >
                        邀请码管理
                      </Button>
                    </Grid>
                  </Grid>
                </Paper>
              )}
              
              {/* 账户管理卡片 - 仅当前用户可见 */}
              {userInfo.isCurrentUser && (
                <Paper elevation={3} sx={{ 
                  p: 3, 
                  mb: 4,
                  borderRadius: 3,
                  background: 'linear-gradient(135deg, #fff0f5 0%, #fce4ec 100%)',
                  boxShadow: '0 4px 20px rgba(200, 100, 255, 0.1)',
                }}>
                  <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
                    账户管理
                  </Typography>
                  <Grid container spacing={3} sx={{ mt: 1 }}>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={() => handleOpen('nickname')}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
                          }
                        }}
                      >
                        修改昵称
                      </Button>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Button 
                        fullWidth
                        variant="contained"
                        onClick={() => handleOpen('password')}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
                          color: 'white',
                          fontWeight: 'bold',
                          '&:hover': {
                            background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
                          }
                        }}
                      >
                        修改密码
                      </Button>
                    </Grid>
                  </Grid>
                </Paper>
              )}
            </>
          )}
        </Box>
      </Container>
      
      {/* 正在关注列表弹窗 */}
      {userInfo.isCurrentUser && (
        <Dialog open={openListDialog === 'following'} onClose={() => setOpenListDialog('')} maxWidth="xs" fullWidth>
          <DialogTitle>正在关注</DialogTitle>
          <DialogContent dividers>
            {followingList.length === 0 ? (
              <Typography color="text.secondary">暂无正在关注的人</Typography>
            ) : (
              followingList.map(user => (
                <Box key={user.id} sx={{ display: 'flex', alignItems: 'center', mb: 2, justifyContent: 'space-between' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar src={user.avatar} sx={{ mr: 2 }} />
                    <Box>
                      <Typography>{user.nickname}</Typography>
                      <Typography color="text.secondary" sx={{ fontSize: 13 }}>{user.email}</Typography>
                    </Box>
                  </Box>
                  <IconButton
                    onClick={() => handleOpenChat(user)}
                    size="small"
                    color="primary"
                  >
                    <MailOutlineIcon />
                  </IconButton>
                </Box>
              ))
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setOpenListDialog('')}>关闭</Button>
          </DialogActions>
        </Dialog>
      )}
      {/* 关注者列表弹窗 */}
      {userInfo.isCurrentUser && (
        <Dialog open={openListDialog === 'followers'} onClose={() => setOpenListDialog('')} maxWidth="xs" fullWidth>
          <DialogTitle>关注者</DialogTitle>
          <DialogContent dividers>
            {followersList.length === 0 ? (
              <Typography color="text.secondary">暂无关注者</Typography>
            ) : (
              followersList.map(user => (
                <Box key={user.id} sx={{ display: 'flex', alignItems: 'center', mb: 2, justifyContent: 'space-between' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar src={user.avatar} sx={{ mr: 2 }} />
                    <Box>
                      <Typography>{user.nickname}</Typography>
                      <Typography color="text.secondary" sx={{ fontSize: 13 }}>{user.email}</Typography>
                    </Box>
                  </Box>
                  <IconButton
                    onClick={() => handleOpenChat(user)}
                    size="small"
                    color="primary"
                  >
                    <MailOutlineIcon />
                  </IconButton>
                </Box>
              ))
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setOpenListDialog('')}>关闭</Button>
          </DialogActions>
        </Dialog>
      )}
      {/* 私信对话弹窗 */}
      {userInfo.isCurrentUser && (
        <Dialog open={openChat.open} onClose={handleCloseChat} maxWidth="xs" fullWidth>
          <DialogTitle>与 {openChat.user?.nickname} 私信</DialogTitle>
          <DialogContent dividers sx={{ minHeight: 180 }}>
            {chatHistory.map((msg, idx) => (
              <Box key={idx} sx={{ mb: 1, textAlign: msg.from === '我' ? 'right' : 'left' }}>
                <Typography variant="body2" color={msg.from === '我' ? 'primary' : 'text.secondary'}>
                  {msg.from}：{msg.content}
                </Typography>
              </Box>
            ))}
          </DialogContent>
          <DialogActions sx={{ display: 'flex', alignItems: 'center' }}>
            <TextField
              size="small"
              placeholder="输入消息..."
              value={chatInput}
              onChange={e => setChatInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleSendChat(); }}
              sx={{ flex: 1 }}
            />
            <Button onClick={handleSendChat} variant="contained">发送</Button>
            <Button onClick={handleCloseChat}>关闭</Button>
          </DialogActions>
        </Dialog>
      )}
      {/* 记录弹窗 */}
      {userInfo.isCurrentUser && (
        <Dialog open={openRecord} onClose={() => setOpenRecord(false)} maxWidth="sm" fullWidth>
          <DialogTitle>{recordType === 'upload' ? '上传记录' : '下载记录'}</DialogTitle>
          <DialogContent dividers>
            {recordList.length === 0 ? (
              <Typography color="text.secondary">暂无记录</Typography>
            ) : (
              <>
                
                
                {recordList.map((record, index) => (
                  <Box key={index} sx={{ mb: 2, p: 1, borderBottom: '1px solid #f0f0f0' }}>
                    <Typography variant="subtitle1" fontWeight="bold">
                      {record.filename || record.title || record.name || '未命名种子'}
                    </Typography>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 1 }}>
                      <Typography variant="body2" color="text.secondary">
                        {record.actionTime ? new Date(record.actionTime).toLocaleString() : (record.time || record.date || new Date().toLocaleString())}
                      </Typography>
                    </Box>
                    {record.torrentId && (
                      <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
                        种子ID: {record.torrentId}
                      </Typography>
                    )}
                    {record.score && (
                      <Typography sx={{ fontSize: 14, mt: 0.5 }} color={record.score.toString().startsWith('+') ? 'success.main' : 'error.main'}>
                        ⭐ 积分：{record.score}
                      </Typography>
                    )}
                  </Box>
                ))}
              </>
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setOpenRecord(false)}>关闭</Button>
          </DialogActions>
        </Dialog>
      )}
      {/* 邀请码弹窗 */}
      <Dialog 
        open={openInviteDialog} 
        onClose={() => setOpenInviteDialog(false)}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 3,
            boxShadow: '0 10px 30px rgba(200, 100, 255, 0.2)',
            overflow: 'hidden'
          }
        }}
      >
        <DialogTitle sx={{ 
          backgroundColor: '#f8bbd0', 
          color: '#8e24aa',
          fontWeight: 'bold'
        }}>邀请码管理</DialogTitle>
        <DialogContent sx={{ mt: 2 }}>
          <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa' }}>我的邀请码</Typography>
          {inviteCodes.length === 0 ? (
            <Typography sx={{ color: '#9e9e9e', my: 2 }}>暂无可用邀请码</Typography>
          ) : (
            <Box sx={{ my: 2 }}>
              {inviteCodes.map((code, index) => (
                <Box 
                  key={index}
                  sx={{ 
                    p: 2, 
                    mb: 1, 
                    border: '1px solid #f3e5f5', 
                    borderRadius: 2,
                    backgroundColor: '#fff9fc',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                  }}
                >
                  <Typography sx={{ fontFamily: 'monospace', fontWeight: 'bold', color: '#d81b60' }}>
                    {code.code}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#9e9e9e' }}>
                    {code.used ? '已使用' : '未使用'}
                  </Typography>
                </Box>
              ))}
            </Box>
          )}
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
            <Button 
              variant="contained" 
              onClick={handleGenerateInviteCode}
              sx={{
                borderRadius: 2,
                background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
                color: 'white',
                fontWeight: 'bold',
                px: 4,
                py: 1,
                '&:hover': {
                  background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
                }
              }}
            >
              生成新邀请码
            </Button>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2, backgroundColor: '#fafafa' }}>
          <Button 
            onClick={() => setOpenInviteDialog(false)}
            sx={{ 
              color: '#9e9e9e',
              '&:hover': { backgroundColor: '#f5f5f5' }
            }}
          >
            关闭
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 表单对话框 */}
      <Dialog 
        open={!!openDialog} 
        onClose={handleClose}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 3,
            boxShadow: '0 10px 30px rgba(200, 100, 255, 0.2)',
            overflow: 'hidden'
          }
        }}
      >
        <DialogTitle sx={{ 
          backgroundColor: '#f8bbd0', 
          color: '#8e24aa',
          fontWeight: 'bold'
        }}>
          {openDialog === 'nickname' && '修改昵称'}
          {openDialog === 'email' && '修改邮箱'}
          {openDialog === 'password' && '修改密码'}
        </DialogTitle>
        <DialogContent sx={{ mt: 2 }}>
          {/* 昵称修改表单 */}
          {openDialog === 'nickname' && (
            <TextField
              label="新昵称"
              fullWidth
              value={form.nickname}
              onChange={handleFormChange('nickname')}
              error={!!formError.nickname}
              helperText={formError.nickname}
              sx={{ mt: 1 }}
            />
          )}
          
          {/* 邮箱修改表单 */}
          {openDialog === 'email' && (
            <TextField
              label="新邮箱"
              type="email"
              fullWidth
              value={form.email}
              onChange={handleFormChange('email')}
              error={!!formError.email}
              helperText={formError.email}
              sx={{ mt: 1 }}
            />
          )}
          
          {/* 密码修改表单 */}
          {openDialog === 'password' && (
            <>
              <TextField
                label="当前密码"
                type="password"
                fullWidth
                value={form.password}
                onChange={handleFormChange('password')}
                error={!!formError.password}
                helperText={formError.password}
                sx={{ mt: 1, mb: 2 }}
              />
              <TextField
                label="新密码"
                type="password"
                fullWidth
                value={form.newPassword}
                onChange={handleFormChange('newPassword')}
                error={!!formError.newPassword}
                helperText={formError.newPassword}
                sx={{ mb: 2 }}
              />
              <TextField
                label="确认新密码"
                type="password"
                fullWidth
                value={form.confirmPassword}
                onChange={handleFormChange('confirmPassword')}
                error={!!formError.confirmPassword}
                helperText={formError.confirmPassword}
                sx={{ mb: 2 }}
              />
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <TextField
                  label="验证码"
                  fullWidth
                  value={form.code}
                  onChange={handleFormChange('code')}
                  error={!!formError.code}
                  helperText={formError.code}
                  sx={{ mr: 1 }}
                />
                <Button 
                  variant="outlined"
                  onClick={() => {
                    const userEmail = localStorage.getItem('email') || userInfo.email;
                    console.log("Sending verification code to:", userEmail);
                    
                    // 防止重复点击
                    const button = document.activeElement;
                    if (button) button.disabled = true;
                    
                    sendPasswordResetCode(userEmail)
                      .then(res => {
                        console.log("Verification code response:", res);
                        setSnackbar({
                          open: true,
                          message: '验证码已发送',
                          severity: 'success'
                        });
                      })
                      .catch(err => {
                        console.error("Failed to send verification code:", err);
                        setSnackbar({
                          open: true,
                          message: '验证码发送失败: ' + (err.response?.data?.message || err.message || '未知错误'),
                          severity: 'error'
                        });
                      })
                      .finally(() => {
                        // 恢复按钮状态
                        if (button) button.disabled = false;
                      });
                  }}
                  sx={{ 
                    minWidth: 120,
                    borderColor: '#d81b60',
                    color: '#d81b60',
                    '&:hover': {
                      borderColor: '#c2185b',
                      backgroundColor: '#fce4ec',
                    }
                  }}
                >
                  获取验证码
                </Button>
              </Box>
            </>
          )}
          
          {/* 头像修改功能已移除 */}
        </DialogContent>
        <DialogActions sx={{ p: 2, backgroundColor: '#fafafa' }}>
          <Button 
            onClick={handleClose}
            sx={{ 
              color: '#9e9e9e',
              '&:hover': { backgroundColor: '#f5f5f5' }
            }}
          >
            取消
          </Button>
          <Button 
            onClick={handleSave}
            variant="contained"
            sx={{
              borderRadius: 2,
              background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
              color: 'white',
              fontWeight: 'bold',
              '&:hover': {
                background: 'linear-gradient(45deg, #6a1b9a 30%, #c2185b 90%)',
              }
            }}
          >
            保存
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Snackbar提示 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        sx={{ 
          '& .MuiAlert-root': {
            borderRadius: 3,
            boxShadow: '0 4px 20px rgba(200, 100, 255, 0.2)',
          }
        }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity} 
          sx={{ 
            width: '100%',
            ...(snackbar.severity === 'success' && {
              backgroundColor: '#f8bbd0',
              color: '#8e24aa',
              '& .MuiAlert-icon': { color: '#d81b60' }
            }),
            ...(snackbar.severity === 'error' && {
              backgroundColor: '#ffebee',
              color: '#c62828',
              '& .MuiAlert-icon': { color: '#d32f2f' }
            })
          }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}

export default Profile; 